package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.Result;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional
    public Result addCart(ShoppingCartDTO dto) {
        //获取当前用户
        Long currentId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        ShoppingCart cart = shoppingCartMapper.selectOne(dto,currentId);
        if (cart == null) {
            cart = new ShoppingCart();
            BeanUtils.copyProperties(dto,cart);
            cart.setUserId(currentId);
            cart.setCreateTime(LocalDateTime.now());
            cart.setNumber(1);

            //还需要判断添加的是套餐还是菜品，补全不同的数据
            if (dto.getDishId() != null) {
                //添加的是菜品，查询菜品信息
                Dish dish = dishMapper.selectById(dto.getDishId());
                cart.setName(dish.getName());
                cart.setImage(dish.getImage());
                cart.setAmount(dish.getPrice());
            } else {
                //添加的是套餐，查询套餐信息
                Setmeal setmeal = setmealMapper.selectById(Math.toIntExact(dto.getSetmealId()));
                cart.setName(setmeal.getName());
                cart.setImage(setmeal.getImage());
                cart.setAmount(setmeal.getPrice());
            }

            //保存到数据库里
            shoppingCartMapper.insert(cart);
        } else {
            //在购物车中，要修改购物车中商品的数量+1
            shoppingCartMapper.updateNumber(cart.getId(),1);
        }
        return Result.success();
    }

    @Override
    public Result queryCart() {
        Long currentUser = BaseContext.getCurrentId();
        List<ShoppingCart> cartList = shoppingCartMapper.selectListByUser(currentUser);
        return Result.success(cartList);
    }

    @Override
    public Result cleanCart() {
        shoppingCartMapper.deleteByUser(BaseContext.getCurrentId());
        return Result.success();
    }
}
